package com.movitech.mobile.cz.base.bizconfig.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.bizconfig.entity.SSuppliersCategory;
import com.movitech.mobile.cz.base.bizconfig.entity.ext.ExtSSuppliersCategory;
import com.movitech.mobile.cz.base.bizconfig.mapper.SSuppliersCategoryMapper;
import com.movitech.mobile.cz.base.bizconfig.mapper.ext.ExtSSuppliersCategoryMapper;
import com.movitech.mobile.cz.base.bizconfig.service.SSuppliersCategoryService;
import com.movitech.mobile.cz.base.common.aop.ServiceThrowable;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.IdGenUtils;
import com.movitech.mobile.cz.base.common.util.IntegerUtils;
import com.movitech.mobile.cz.base.common.utils.StringUtils;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.modules.suppliers.vo.BuildTree;
import com.movitech.mobile.cz.base.modules.suppliers.vo.Tree;
import com.movitech.mobile.cz.base.sys.bizvo.SuppliersCategoryFindRequest;
import com.movitech.mobile.cz.base.sys.bizvo.SuppliersCategoryRequestVO;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 供应商分类 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-02-28
 */
@Service("sSuppliersCategoryService")
@Transactional
public class SSuppliersCategoryServiceImpl extends ServiceImpl<SSuppliersCategoryMapper, SSuppliersCategory> implements SSuppliersCategoryService {

    @Autowired
    private ExtSSuppliersCategoryMapper extSSuppliersCategoryMapper;

    @Override
    public List<ExtSSuppliersCategory> selectByCode(String code) {
        List<ExtSSuppliersCategory> categories = extSSuppliersCategoryMapper.selectByCode(code);
        return categories;
    }

    @Override
    public RestReturnResult<Object> getSuppliersCategoryTree() {
        LicenseUtil.INSTANCE.validate();
        RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("del_flag", CommonConstants.NO_INTEGER);
        List<SSuppliersCategory> supplierCateList = baseMapper.selectByMap(map);

        List<Tree<SSuppliersCategory>> nodes = new ArrayList<Tree<SSuppliersCategory>>();
        if (supplierCateList != null && supplierCateList.size() > 0) {
            for (SSuppliersCategory suppliersCategory : supplierCateList) {
                Tree<SSuppliersCategory> t = new Tree<SSuppliersCategory>();
                t.setId(suppliersCategory.getId());
                t.setText(suppliersCategory.getCategoryName());
                t.setParentId(suppliersCategory.getParentId());

                nodes.add(t);
            }

            List<Tree<SSuppliersCategory>> tree = null;
            if (nodes != null && nodes.size() > 0) {
                tree = BuildTree.build(nodes);

                hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, tree);
            } else {
                hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } else {
            hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
        }

        return hResult;
    }

    /**
     * 同一级别供方分类下名称重复校验
     *
     * @param parentId
     * @param categoryName
     * @return
     */
    private boolean validateDuplicateCategoryName(String parentId, String categoryName) {

        List<ExtSSuppliersCategory> suppliersCategoryList = extSSuppliersCategoryMapper.selectByCategoryNameAndParentId(parentId, categoryName);

        LicenseUtil.INSTANCE.validate();
        if (suppliersCategoryList != null && suppliersCategoryList.size() > 0) {//存在即重复
            return true;
        }

        return false;
    }

    @Override
    public RestReturnResult<Object> saveOrUpdateSuppliersCategory(SuppliersCategoryRequestVO suppliersCategoryRequestVO) {
        RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {
            SSuppliersCategory suppliersCategory = null;
            if (suppliersCategoryRequestVO != null && StringUtils.isNotBlank(suppliersCategoryRequestVO.getCategoryName())) {

                if (this.validateDuplicateCategoryName(suppliersCategoryRequestVO.getParentId(), suppliersCategoryRequestVO.getCategoryName())) {
                    throw new RuntimeException("该上级分类下供方分类名称已存在", new ServiceThrowable());
                }

                if (StringUtils.isNotEmpty(suppliersCategoryRequestVO.getId())) { //update

                    suppliersCategory = baseMapper.selectById(suppliersCategoryRequestVO.getId());
                    if (suppliersCategory != null) {
                        suppliersCategory.setCategoryName(suppliersCategoryRequestVO.getCategoryName());
                        suppliersCategory.setParentId(suppliersCategoryRequestVO.getParentId());
                        suppliersCategory.setRemarks(suppliersCategoryRequestVO.getRemarks());
                        suppliersCategory.setCategoryLevel(suppliersCategoryRequestVO.getCategoryLevel());
                        if (suppliersCategoryRequestVO.getCategoryStatus() != null) {
                            suppliersCategory.setCategoryStatus(suppliersCategoryRequestVO.getCategoryStatus());
                        }
                        Date updateDate = new Date();
                        String userId = UserUtils.getCurrentUserId();
                        suppliersCategory.setUpdateBy(userId);
                        suppliersCategory.setUpdateDate(updateDate);
                        suppliersCategory.setDelFlag(CommonConstants.NO_INTEGER);

                        baseMapper.updateById(suppliersCategory);

                        hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[1], CommonConstants.SUCCESS_DESCS[1]);
                    } else { //数据不存在
                        hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                    }

                    LicenseUtil.INSTANCE.validate();
                } else { //insert

                    suppliersCategory = new SSuppliersCategory();
                    suppliersCategory.setId(IdGenUtils.uuid());
                    suppliersCategory.setCategoryName(suppliersCategoryRequestVO.getCategoryName());
                    suppliersCategory.setParentId(suppliersCategoryRequestVO.getParentId());
                    suppliersCategory.setRemarks(suppliersCategoryRequestVO.getRemarks());
                    suppliersCategory.setCategoryLevel(suppliersCategoryRequestVO.getCategoryLevel());
                    suppliersCategory.setCategoryStatus(0);
                    suppliersCategory.setSiteInspectionSetFlag(0);
                    suppliersCategory.setPerformEvalPostSetFlag(0);
                    suppliersCategory.setPerformEvalProcSetFlag(0);
                    suppliersCategory.setEvaluateScoreSetFlag(0);
                    suppliersCategory.setTechnicalScoreSetFlag(0);
                    suppliersCategory.setTechnicalDarkScoreSetFlag(0);
                    suppliersCategory.setPmInterviewScoreSetFlag(0);
                    Date createDate = new Date();
                    String userId = UserUtils.getCurrentUserId();
                    suppliersCategory.setCreateBy(userId);
                    suppliersCategory.setCreateDate(createDate);
                    suppliersCategory.setUpdateBy(userId);
                    suppliersCategory.setUpdateDate(createDate);
                    suppliersCategory.setDelFlag(CommonConstants.NO_INTEGER);

                    baseMapper.insert(suppliersCategory);

                    hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[0], CommonConstants.SUCCESS_DESCS[0]);
                }
            } else {//请求数据出错
                hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

        return hResult;
    }

    @Override
    public RestReturnResult<Object> updateSuppliersCategoryForDel(String id) {
        RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        if (StringUtils.isNotEmpty(id)) {

            SSuppliersCategory suppliersCategory = extSSuppliersCategoryMapper.selectById(id);
            if (suppliersCategory != null) {

                SSuppliersCategory parent = extSSuppliersCategoryMapper.getByParentId(suppliersCategory.getId());
                if (parent != null) {// 存在下级类别，不可以删除
                    hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[6], CommonConstants.ERROR_DESCS[6]);
                    return hResult;
                }

                LicenseUtil.INSTANCE.validate();
                suppliersCategory.setDelFlag(CommonConstants.YES_INTEGER);

                Date updateDate = new Date();
                String userId = UserUtils.getCurrentUserId();
                suppliersCategory.setUpdateBy(userId);
                suppliersCategory.setUpdateDate(updateDate);

                extSSuppliersCategoryMapper.deleteById(id);

            } else {//数据不存在
                hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
            }

            hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[2], CommonConstants.SUCCESS_DESCS[2]);
        } else {
            hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
        }

        return hResult;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public RestReturnResult<Object> updateSuppliersCategoryStatus(SuppliersCategoryRequestVO suppliersCategoryRequestVO) {
        RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        if (suppliersCategoryRequestVO != null) {
            if (StringUtils.isNotEmpty(suppliersCategoryRequestVO.getId())) {

                SSuppliersCategory suppliersCategory = baseMapper.selectById(suppliersCategoryRequestVO.getId());
                if (suppliersCategory != null) {
                    Date updateDate = new Date();
                    String userId = UserUtils.getCurrentUserId();
                    updateCategoryStatus(suppliersCategory, suppliersCategoryRequestVO.getCategoryStatus(), userId, updateDate);

//                    suppliersCategory.setCategoryStatus(suppliersCategoryRequestVO.getCategoryStatus());
//                    suppliersCategory.setUpdateBy(userId);
//                    suppliersCategory.setUpdateDate(updateDate);
//                    baseMapper.updateById(suppliersCategory);


                } else {//数据不存在
                    hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                }
                LicenseUtil.INSTANCE.validate();

                if (CommonConstants.YES_INTEGER == suppliersCategoryRequestVO.getCategoryStatus()) {//启用
                    hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[3], CommonConstants.SUCCESS_DESCS[3]);
                } else {//停用
                    hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[4], CommonConstants.SUCCESS_DESCS[4]);
                }
            } else {
                hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
            }
        } else {//请求数据出错
            hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
        }

        return hResult;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void updateCategoryStatus(SSuppliersCategory suppliersCategory, Integer categoryStatus, String userId, Date updateDate) {
        if (suppliersCategory != null) {
            suppliersCategory.setCategoryStatus(categoryStatus);
            suppliersCategory.setUpdateBy(userId);
            suppliersCategory.setUpdateDate(updateDate);
            baseMapper.updateById(suppliersCategory);

            //子节点供方更新
            EntityWrapper wrapper = new EntityWrapper();
            SSuppliersCategory obj = new SSuppliersCategory();
            obj.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
            obj.setParentId(suppliersCategory.getId());
            wrapper.setEntity(obj);
            List<SSuppliersCategory> ls = baseMapper.selectList(wrapper);
            if (ls != null && ls.size() > 0) {
                for (SSuppliersCategory category : ls) {
                    updateCategoryStatus(category, categoryStatus, userId, updateDate);
                }
            }
        }
    }

    @Override
    public String getSupplierCategoryNames(String[] supplierCategoryIdArr) {
        return extSSuppliersCategoryMapper.getSupplierCategoryNames(supplierCategoryIdArr);
    }

    @Override
    public String getRootSupplierCategoryNames(String categoryIds) {
        if (StringUtils.isNotEmpty(categoryIds)) {
            List<ExtSSuppliersCategory> supplierCateList = extSSuppliersCategoryMapper.selectAll();
            Map<String, ExtSSuppliersCategory> map = new HashMap<>();
            if (supplierCateList != null && supplierCateList.size() > 0) {
                for (ExtSSuppliersCategory suppliersCategory : supplierCateList) {
                    map.put(suppliersCategory.getId(), suppliersCategory);
                }
            }
            LicenseUtil.INSTANCE.validate();
            String[] categoryIdArr = categoryIds.split(",");
            StringBuffer categoryNames = new StringBuffer();
            if (categoryIdArr != null && categoryIdArr.length > 0) {
                for (int i = 0; i < categoryIdArr.length; i++) {
                    ExtSSuppliersCategory category = this.getRootSupplierCategory(categoryIdArr[i], map);
                    if (category != null) {
                        if (i > 0) {
                            categoryNames.append(",");
                        }
                        categoryNames.append(category.getCategoryName());
                    }
                }
            }
            return categoryNames.toString();
        }

        return "";
    }

    private ExtSSuppliersCategory getRootSupplierCategory(String categoryId, Map<String, ExtSSuppliersCategory> categoryMap) {
        ExtSSuppliersCategory category = categoryMap.get(categoryId);
        if (category != null) {
            String parentId = category.getParentId();
            if (StringUtils.isNotEmpty(parentId)) {
                getRootSupplierCategory(category.getParentId(), categoryMap);
            } else {
                return category;
            }
        }
        return null;
    }

    @Override
    public RestReturnResult<Object> getSuppliersCategoryTreeByLevel(String level) {
        RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("del_flag", CommonConstants.NO_INTEGER);
//        List<SSuppliersCategory> supplierCateList = baseMapper.selectByMap(map);
        List<SSuppliersCategory> supplierCateList = extSSuppliersCategoryMapper.selectSupplierCateListByLevel(level);

        List<Tree<SSuppliersCategory>> nodes = new ArrayList<Tree<SSuppliersCategory>>();
        if (supplierCateList != null && supplierCateList.size() > 0) {
            for (SSuppliersCategory suppliersCategory : supplierCateList) {
                Tree<SSuppliersCategory> t = new Tree<SSuppliersCategory>();
                t.setId(suppliersCategory.getId());
                t.setText(suppliersCategory.getCategoryName());
                t.setParentId(suppliersCategory.getParentId());
                t.setCategoryLevel(suppliersCategory.getCategoryLevel());
                nodes.add(t);
            }

            LicenseUtil.INSTANCE.validate();
            List<Tree<SSuppliersCategory>> tree = null;
            if (nodes != null && nodes.size() > 0) {
                tree = BuildTree.build(nodes);

                hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, tree);
            } else {
                hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } else {
            hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
        }

        return hResult;
    }


    @Override
    public RestReturnResult<Object> findSuppliersCategoryTreeList(SuppliersCategoryFindRequest suppliersCategoryFindRequest) {
        RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);
        Map<String, Object> resultMap = new HashMap<String, Object>();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageSize", suppliersCategoryFindRequest.getPageSize());
        if (suppliersCategoryFindRequest.getPageSize() == 0) {
            suppliersCategoryFindRequest.setPageSize(10);
        }
        map.put("currentRecordNum", (suppliersCategoryFindRequest.getPageNumber() - 1) * suppliersCategoryFindRequest.getPageSize());

        map.put("categoryName", suppliersCategoryFindRequest.getCategoryName());
        map.put("categoryStatus", suppliersCategoryFindRequest.getCategoryStatus());
        map.put("categoryLevel", suppliersCategoryFindRequest.getCategoryLevel());

        LicenseUtil.INSTANCE.validate();
        Integer count = extSSuppliersCategoryMapper.findSuppliersCategoryTreeListCount(map);
        resultMap.put("count", (count == null ? 0 : count));
        List<ExtSSuppliersCategory> list = extSSuppliersCategoryMapper.findSuppliersCategoryTreeList(map);

        List<Tree<ExtSSuppliersCategory>> nodes = new ArrayList<Tree<ExtSSuppliersCategory>>();
        if (list != null && list.size() > 0) {
            for (ExtSSuppliersCategory suppliersCategory : list) {
                Tree<ExtSSuppliersCategory> t = new Tree<ExtSSuppliersCategory>();
                t.setId(suppliersCategory.getId());
                t.setText(suppliersCategory.getCategoryName());
                t.setParentId(suppliersCategory.getParentId());
                t.setCategoryName(suppliersCategory.getCategoryName());
                t.setRemarks(suppliersCategory.getRemarks());
                t.setCategoryLevel(suppliersCategory.getCategoryLevel());
                t.setCategoryStatus(suppliersCategory.getCategoryStatus());
                t.setSiteInspectionSetFlag(IntegerUtils.convertNullToZero(suppliersCategory.getSiteInspectionSetFlag()));
                t.setPerformEvalPostSetFlag(IntegerUtils.convertNullToZero(suppliersCategory.getPerformEvalPostSetFlag()));
                t.setPerformEvalProcSetFlag(IntegerUtils.convertNullToZero(suppliersCategory.getPerformEvalProcSetFlag()));
                t.setEvaluateScoreSetFlag(IntegerUtils.convertNullToZero(suppliersCategory.getEvaluateScoreSetFlag()));
                t.setTechnicalScoreSetFlag(IntegerUtils.convertNullToZero(suppliersCategory.getTechnicalScoreSetFlag()));
                t.setTechnicalDarkScoreSetFlag(IntegerUtils.convertNullToZero(suppliersCategory.getTechnicalDarkScoreSetFlag()));
                t.setPmInterviewScoreSetFlag(IntegerUtils.convertNullToZero(suppliersCategory.getPmInterviewScoreSetFlag()));

                nodes.add(t);
            }

            List<Tree<ExtSSuppliersCategory>> tree = null;
            if (nodes != null && nodes.size() > 0) {
                tree = BuildTree.build(nodes);
                resultMap.put("tree", tree);
                hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, resultMap);
            } else {
                hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } else {
            hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
        }


        return hResult;
    }


    @Override
    public List<String> selectShowIdsByParentId(String parentId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("show_flag", 1).eq("del_flag", 0);
        if (StringUtils.isEmpty(parentId)) {
            entityWrapper.isNull("parent_id");
        } else {
            entityWrapper.eq("parent_id", parentId);
        }
        List<Object> o = selectObjs(entityWrapper.setSqlSelect("id"));
        return (List<String>) (List) o;
    }
}
